﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChurchData.Business;

namespace ChurchData
{
    public partial class AddRelationshipDialog : Form
    {
        #region Fields / Properties
        private int PeoplePK { get; set; }
        private string ParentFirstName { get; set; }
        private string ParentLastName { get; set; }
        private AddDialogMode _mode { get; set; }
        /// <summary>
        /// If they are adding people to the household and didn't find them already in the system they
        /// can click the new button to create a new person in the household.  The form will set this
        /// and then close letting the parent form handle creating the person.
        /// </summary>
        public bool CreateNewPersonInHousehold { get; set; }
        public string FirstName
        {
            get
            {
                return this.txtFirstName.Text.Trim();
            }
        }
        public string LastName
        {
            get
            {
                return this.txtLastName.Text.Trim();
            }
        }
        
        #endregion Fields / Properties

        #region Constructor & Form Load
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="mode">AddRelationshipDialog.AddDialogMode, this form is used for both adding Household members and adding relationships</param>
        /// <param name="lastName">Optional parm, defaults the last name text box</param>
        public AddRelationshipDialog(AddDialogMode mode, int peoplePK, string lastName, string firstName)
        {
            InitializeComponent();
            this.CreateNewPersonInHousehold = false;

            this._mode = mode;
            this.PeoplePK = peoplePK;
            this.txtLastName.Text = lastName;
            this.ParentFirstName = firstName;
            this.ParentLastName = lastName;
        }

        private void AddRelationshipDialog_Load(object sender, EventArgs e)
        {
            if (_mode == AddDialogMode.Relationship)
            {
                btnAddNew.Visible = false;
                this.Height = 443;
                this.btnAddSelected.Location = new Point(11, 357);
                this.PopulateRelationshipGrid();
            }
            else
            {
                this.Height = 191;
            }

            if (_mode == AddDialogMode.JoinHousehold)
            {
                btnAddNew.Visible = false;
                btnAddSelected.Text = "Join selected";
            }

            this.txtFirstName.Focus();
        }

        public enum AddDialogMode
        {
            HouseholdMember,
            Relationship,
            JoinHousehold
        }

        private void PopulateRelationshipGrid()
        {
            LKRelationshipBO rBO = new LKRelationshipBO();
            List<SimpleRelationship> relationships = rBO.GetRelationshipsForwardAndBackward();
            grdRelationship.DataSource = relationships;
            grdRelationship.Columns["LKRelationshipPK"].Visible = false;
            grdRelationship.Columns["Flipped"].Visible = false;
            grdRelationship.Columns["DescriptionOne"].HeaderText = ParentFirstName + " " + ParentLastName;
            grdRelationship.Columns["DescriptionTwo"].HeaderText = "";
        }
        #endregion Constructor & Form Load

        #region Control Events
        private void txtFirstName_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnSearch.PerformClick();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            PeopleBO pBO = new PeopleBO();
            List<PeopleSearchResults> ds = new List<PeopleSearchResults>();

            if (_mode == AddDialogMode.Relationship)
                ds = pBO.LookupPeopleNotRelatedYet(PeoplePK, txtFirstName.Text.Trim(), txtLastName.Text.Trim());
            else if (_mode == AddDialogMode.HouseholdMember)
                ds = pBO.LookupPeopleNotInHouseholdYet(PeoplePK, txtFirstName.Text.Trim(), txtLastName.Text.Trim());
            else if (_mode == AddDialogMode.JoinHousehold)
                ds = pBO.LookupHeadsOfHousehold(txtFirstName.Text.Trim(), txtLastName.Text.Trim());

            grdPeople.DataSource = ds;
            grdPeople.Columns["PeoplePK"].Visible = false;
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            this.CreateNewPersonInHousehold = true;
            this.Close();
        }

        private void btnAddSelected_Click(object sender, EventArgs e)
        {
            if (this.grdPeople.SelectedRows.Count == 0)
            {
                MessageBox.Show("Please select who you'd like to add");
                return;
            }

            if (this._mode == AddDialogMode.HouseholdMember)
                AddToHousehold();

            if (this._mode == AddDialogMode.JoinHousehold)
                JoinHousehold();

            if (this._mode == AddDialogMode.Relationship)
                AddRelationship();
        }

        private void grdPeople_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.btnAddSelected.PerformClick();
        }

        private void grdPeople_SelectionChanged(object sender, EventArgs e)
        {
            if (grdPeople.SelectedRows.Count == 0)
                grdRelationship.Columns["DescriptionTwo"].HeaderText = "";
            else
            {
                string firstName = grdPeople.SelectedRows[0].Cells["FirstName"].Value.ToString().Trim();
                string lastName = grdPeople.SelectedRows[0].Cells["LastName"].Value.ToString().Trim();
                grdRelationship.Columns["DescriptionTwo"].HeaderText = firstName + " " + lastName;
            }
        }

        #endregion Control Events

        #region Action Methods
        private void AddToHousehold()
        {
            // First find out which household the person who this was initiated under is in
            PeopleBO pBO = new PeopleBO();
            People drP = pBO.GetRecordByPK(this.PeoplePK);
            int? householdFK = drP.HouseholdFK;

            // Now update the selected person to the same household
            pBO.UpdateHousehold((int)grdPeople.SelectedRows[0].Cells["PeoplePK"].Value, householdFK);
            this.Close();
        }

        private void JoinHousehold()
        {
            PeopleBO pBO = new PeopleBO();
            People drP = pBO.GetRecordByPK((int)grdPeople.SelectedRows[0].Cells["PeoplePK"].Value);
            int? householdFK = drP.HouseholdFK;

            pBO.UpdateHousehold(this.PeoplePK, householdFK);
            this.Close();
        }

        private void AddRelationship()
        {
            if (grdRelationship.SelectedRows.Count == 0)
            {
                MessageBox.Show("Please select a relationship pair");
                return;
            }

            // The PeopleRelated.FromPeopleFK always goes to LKRelationship.DescriptionOne
            // The PeopleRelated.ToPeopleFK always goes to LKRelationship.DescriptionTwo
            bool flipped = Convert.ToBoolean(grdRelationship.SelectedRows[0].Cells["Flipped"].Value);
            int lkRelationshipFK = Convert.ToInt32(grdRelationship.SelectedRows[0].Cells["LKRelationshipPK"].Value);
            int fromPeopleFK = -1;
            int toPeopleFK = -1;

            if (!flipped)
            {
                fromPeopleFK = PeoplePK;
                toPeopleFK = Convert.ToInt32(grdPeople.SelectedRows[0].Cells["PeoplePK"].Value);
            }
            else
            {
                fromPeopleFK = Convert.ToInt32(grdPeople.SelectedRows[0].Cells["PeoplePK"].Value);
                toPeopleFK = PeoplePK;
            }

            PeopleRelatedBO prBO = new PeopleRelatedBO();
            prBO.AddRelationship(fromPeopleFK, toPeopleFK, lkRelationshipFK);
            this.Close();
        }
        #endregion Action Methods
    }
}
